home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 5 / Skunkware 5.iso / lib / emacs / 19.22 / lisp / forms.el < prev    next >
Text File  |  1993-11-19  |  56KB  |  1,721 lines

  1. ;;; forms.el -- Forms mode: edit a file as a form to fill in.
  2. ;;; Copyright (C) 1991, 1993 Free Software Foundation, Inc.
  3.  
  4. ;; Author: Johan Vromans <jv@nl.net>
  5. ;; Version: $Revision: 2.3 $
  6.  
  7. ;; This file is part of GNU Emacs.
  8.  
  9. ;; GNU Emacs is free software; you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation; either version 2, or (at your option)
  12. ;; any later version.
  13.  
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. ;; GNU General Public License for more details.
  18.  
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  21. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  22.  
  23. ;;; Commentary:
  24.  
  25. ;;; Visit a file using a form.
  26. ;;;
  27. ;;; === Naming conventions
  28. ;;;
  29. ;;; The names of all variables and functions start with 'forms-'.
  30. ;;; Names which start with 'forms--' are intended for internal use, and
  31. ;;; should *NOT* be used from the outside.
  32. ;;;
  33. ;;; All variables are buffer-local, to enable multiple forms visits 
  34. ;;; simultaneously.
  35. ;;; Variable `forms--mode-setup' is local to *ALL* buffers, for it 
  36. ;;; controls if forms-mode has been enabled in a buffer.
  37. ;;;
  38. ;;; === How it works ===
  39. ;;;
  40. ;;; Forms mode means visiting a data file which is supposed to consist
  41. ;;; of records each containing a number of fields.  The records are
  42. ;;; separated by a newline, the fields are separated by a user-defined
  43. ;;; field separater (default: TAB).
  44. ;;; When shown, a record is transferred to an Emacs buffer and
  45. ;;; presented using a user-defined form.  One record is shown at a
  46. ;;; time.
  47. ;;;
  48. ;;; Forms mode is a composite mode.  It involves two files, and two
  49. ;;; buffers.
  50. ;;; The first file, called the control file, defines the name of the
  51. ;;; data file and the forms format.  This file buffer will be used to
  52. ;;; present the forms.
  53. ;;; The second file holds the actual data.  The buffer of this file
  54. ;;; will be buried, for it is never accessed directly.
  55. ;;;
  56. ;;; Forms mode is invoked using M-x forms-find-file control-file .
  57. ;;; Alternativily `forms-find-file-other-window' can be used.
  58. ;;;
  59. ;;; You may also visit the control file, and switch to forms mode by hand
  60. ;;; with M-x forms-mode .
  61. ;;;
  62. ;;; Automatic mode switching is supported if you specify 
  63. ;;; "-*- forms -*-" in the first line of the control file.
  64. ;;; 
  65. ;;; The control file is visited, evaluated using `eval-current-buffer',
  66. ;;; and should set at least the following variables:
  67. ;;;
  68. ;;;    forms-file                [string]
  69. ;;;            The name of the data file.
  70. ;;;
  71. ;;;    forms-number-of-fields            [integer]
  72. ;;;            The number of fields in each record.
  73. ;;;
  74. ;;;    forms-format-list            [list]
  75. ;;;            Formatting instructions.
  76. ;;;
  77. ;;; `forms-format-list' should be a list, each element containing
  78. ;;;
  79. ;;;   - a string, e.g. "hello".  The string is inserted in the forms
  80. ;;;    "as is".
  81. ;;;   
  82. ;;;   - an integer, denoting a field number.
  83. ;;;    The contents of this field are inserted at this point.
  84. ;;;     Fields are numbered starting with number one.
  85. ;;;   
  86. ;;;   - a function call, e.g. (insert "text").
  87. ;;;    This function call is dynamically evaluated and should return a
  88. ;;;     string.  It should *NOT* have side-effects on the forms being
  89. ;;;     constructed.  The current fields are available to the function
  90. ;;;     in the variable `forms-fields', they should *NOT* be modified.
  91. ;;;   
  92. ;;;   - a lisp symbol, that must evaluate to one of the above.
  93. ;;;
  94. ;;; Optional variables which may be set in the control file:
  95. ;;;
  96. ;;;    forms-field-sep                [string, default TAB]
  97. ;;;            The field separator used to separate the
  98. ;;;            fields in the data file.  It may be a string.
  99. ;;;
  100. ;;;    forms-read-only                [bool, default nil]
  101. ;;;            Non-nil means that the data file is visited
  102. ;;;            read-only (view mode) as opposed to edit mode.
  103. ;;;            If no write access to the data file is
  104. ;;;            possible, view mode is enforced. 
  105. ;;;
  106. ;;;    forms-multi-line            [string, default "^K"]
  107. ;;;            If non-null the records of the data file may
  108. ;;;            contain fields that can span multiple lines in
  109. ;;;            the form.
  110. ;;;            This variable denotes the separator character
  111. ;;;            to be used for this purpose.  Upon display, all
  112. ;;;            occurrencies of this character are translated
  113. ;;;            to newlines.  Upon storage they are translated
  114. ;;;            back to the separator character.
  115. ;;;
  116. ;;;    forms-forms-scroll            [bool, default nil]
  117. ;;;            Non-nil means: rebind locally the commands that
  118. ;;;            perform `scroll-up' or `scroll-down' to use
  119. ;;;            `forms-next-field' resp. `forms-prev-field'.
  120. ;;;
  121. ;;;    forms-forms-jump            [bool, default nil]
  122. ;;;            Non-nil means: rebind locally the commands that
  123. ;;;            perform `beginning-of-buffer' or `end-of-buffer'
  124. ;;;            to perform `forms-first-field' resp. `forms-last-field'.
  125. ;;;
  126. ;;;    forms-new-record-filter            [symbol, default nil]
  127. ;;;            If not nil: this should be the name of a 
  128. ;;;            function that is called when a new
  129. ;;;            record is created.  It can be used to fill in
  130. ;;;            the new record with default fields, for example.
  131. ;;;
  132. ;;;    forms-modified-record-filter        [symbol, default nil]
  133. ;;;            If not nil: this should be the name of a 
  134. ;;;            function that is called when a record has
  135. ;;;            been modified.  It is called after the fields
  136. ;;;            are parsed.  It can be used to register
  137. ;;;            modification dates, for example.
  138. ;;;
  139. ;;;    forms-use-text-properties        [bool, see text for default]
  140. ;;;            This variable controls if forms mode should use
  141. ;;;            text properties to protect the form text from being
  142. ;;;            modified (using text-property `read-only').
  143. ;;;            Also, the read-write fields are shown using a
  144. ;;;            distinct face, if possible.
  145. ;;;            This variable defaults to t if running Emacs 19
  146. ;;;            with text properties.
  147. ;;;            The default face to show read-write fields is
  148. ;;;            copied from face `region'.
  149. ;;;
  150. ;;;    forms-ro-face                 [symbol, default 'default]
  151. ;;;            This is the face that is used to show
  152. ;;;            read-only text on the screen.If used, this
  153. ;;;            variable should be set to a symbol that is a
  154. ;;;            valid face.
  155. ;;;            E.g.
  156. ;;;              (make-face 'my-face)
  157. ;;;              (setq forms-ro-face 'my-face)
  158. ;;;
  159. ;;;    forms-rw-face                [symbol, default 'region]
  160. ;;;            This is the face that is used to show
  161. ;;;            read-write text on the screen.
  162. ;;;
  163. ;;; After evaluating the control file, its buffer is cleared and used
  164. ;;; for further processing.
  165. ;;; The data file (as designated by `forms-file') is visited in a buffer
  166. ;;; `forms--file-buffer' which will not normally be shown.
  167. ;;; Great malfunctioning may be expected if this file/buffer is modified
  168. ;;; outside of this package while it is being visited!
  169. ;;;
  170. ;;; Normal operation is to transfer one line (record) from the data file,
  171. ;;; split it into fields (into `forms--the-record-list'), and display it
  172. ;;; using the specs in `forms-format-list'.
  173. ;;; A format routine `forms--format' is built upon startup to format 
  174. ;;; the records according to `forms-format-list'.
  175. ;;;
  176. ;;; When a form is changed the record is updated as soon as this form
  177. ;;; is left.  The contents of the form are parsed using information
  178. ;;; obtained from `forms-format-list', and the fields which are
  179. ;;; deduced from the form are modified.  Fields not shown on the forms
  180. ;;; retain their origional values.  The newly formed record then
  181. ;;; replaces the contents of the old record in `forms--file-buffer'.
  182. ;;; A parse routine `forms--parser' is built upon startup to parse
  183. ;;; the records.
  184. ;;;
  185. ;;; Two exit functions exist: `forms-exit' and `forms-exit-no-save'.
  186. ;;; `forms-exit' saves the data to the file, if modified.
  187. ;;; `forms-exit-no-save` does not.  However, if `forms-exit-no-save'
  188. ;;; is executed and the file buffer has been modified, Emacs will ask
  189. ;;; questions anyway.
  190. ;;;
  191. ;;; Other functions provided by forms mode are:
  192. ;;;
  193. ;;;    paging (forward, backward) by record
  194. ;;;    jumping (first, last, random number)
  195. ;;;    searching
  196. ;;;    creating and deleting records
  197. ;;;    reverting the form (NOT the file buffer)
  198. ;;;    switching edit <-> view mode v.v.
  199. ;;;    jumping from field to field
  200. ;;;
  201. ;;; As an documented side-effect: jumping to the last record in the
  202. ;;; file (using forms-last-record) will adjust forms--total-records if
  203. ;;; needed.
  204. ;;;
  205. ;;; The forms buffer can be in on eof two modes: edit mode or view
  206. ;;; mode.  View mode is a read-only mode, you cannot modify the
  207. ;;; contents of the buffer.
  208. ;;;
  209. ;;; Edit mode commands:
  210. ;;; 
  211. ;;; TAB         forms-next-field
  212. ;;; \C-c TAB     forms-next-field
  213. ;;; \C-c <     forms-first-record
  214. ;;; \C-c >     forms-last-record
  215. ;;; \C-c ?     describe-mode
  216. ;;; \C-c \C-k     forms-delete-record
  217. ;;; \C-c \C-q     forms-toggle-read-only
  218. ;;; \C-c \C-o     forms-insert-record
  219. ;;; \C-c \C-l     forms-jump-record
  220. ;;; \C-c \C-n     forms-next-record
  221. ;;; \C-c \C-p     forms-prev-record
  222. ;;; \C-c \C-s     forms-search
  223. ;;; \C-c \C-x     forms-exit
  224. ;;; 
  225. ;;; Read-only mode commands:
  226. ;;; 
  227. ;;; SPC      forms-next-record
  228. ;;; DEL     forms-prev-record
  229. ;;; ?     describe-mode
  230. ;;; \C-q forms-toggle-read-only
  231. ;;; l     forms-jump-record
  232. ;;; n     forms-next-record
  233. ;;; p     forms-prev-record
  234. ;;; s     forms-search
  235. ;;; x     forms-exit
  236. ;;; 
  237. ;;; Of course, it is also possible to use the \C-c prefix to obtain the
  238. ;;; same command keys as in edit mode.
  239. ;;; 
  240. ;;; The following bindings are available, independent of the mode: 
  241. ;;; 
  242. ;;; [next]      forms-next-record
  243. ;;; [prior]      forms-prev-record
  244. ;;; [begin]      forms-first-record
  245. ;;; [end]      forms-last-record
  246. ;;; [S-TAB]      forms-prev-field
  247. ;;; [backtab] forms-prev-field
  248. ;;;
  249. ;;; For convenience, TAB is always bound to `forms-next-field', so you
  250. ;;; don't need the C-c prefix for this command.
  251. ;;;
  252. ;;; As mentioned above (see `forms-forms-scroll' and `forms-forms-jump')
  253. ;;; the bindings of standard functions `scroll-up', `scroll-down',
  254. ;;; `beginning-of-buffer' and `end-of-buffer' can be locally replaced with
  255. ;;; forms mode functions next/prev record and first/last
  256. ;;; record.
  257. ;;;
  258. ;;; `local-write-file hook' is defined to save the actual data file
  259. ;;; instead of the buffer data, `revert-file-hook' is defined to
  260. ;;; revert a forms to original.
  261.  
  262. ;;; Code:
  263.  
  264. ;;; Global variables and constants:
  265.  
  266. (provide 'forms)            ;;; official
  267. (provide 'forms-mode)            ;;; for compatibility
  268.  
  269. (defconst forms-version (substring "$Revision: 2.3 $" 11 -2)
  270.   "The version number of forms-mode (as string).  The complete RCS id is:
  271.  
  272.   $Id: forms.el,v 2.3 1993/10/21 00:43:51 rms Exp $")
  273.  
  274. (defvar forms-mode-hooks nil
  275.   "Hook functions to be run upon entering Forms mode.")
  276.  
  277. ;;; Mandatory variables - must be set by evaluating the control file.
  278.  
  279. (defvar forms-file nil
  280.   "Name of the file holding the data.")
  281.  
  282. (defvar forms-format-list nil
  283.   "List of formatting specifications.")
  284.  
  285. (defvar forms-number-of-fields nil
  286.   "Number of fields per record.")
  287.  
  288. ;;; Optional variables with default values.
  289.  
  290. (defvar forms-field-sep "\t"
  291.   "Field separator character (default TAB).")
  292.  
  293. (defvar forms-read-only nil
  294.   "Non-nil means: visit the file in view (read-only) mode.
  295. (Defaults to the write access on the data file).")
  296.  
  297. (defvar forms-multi-line "\C-k"
  298.   "If not nil: use this character to separate multi-line fields (default C-k).")
  299.  
  300. (defvar forms-forms-scroll nil
  301.   "*Non-nil means replace scroll-up/down commands in Forms mode.
  302. The replacement commands performs forms-next/prev-record.")
  303.  
  304. (defvar forms-forms-jump nil
  305.   "*Non-nil means redefine beginning/end-of-buffer in Forms mode.
  306. The replacement commands performs forms-first/last-record.")
  307.  
  308. (defvar forms-new-record-filter nil
  309.   "The name of a function that is called when a new record is created.")
  310.  
  311. (defvar forms-modified-record-filter nil
  312.   "The name of a function that is called when a record has been modified.")
  313.  
  314. (defvar forms-fields nil
  315.   "List with fields of the current forms.  First field has number 1.
  316. This variable is for use by the filter routines only. 
  317. The contents may NOT be modified.")
  318.  
  319. (defvar forms-use-text-properties (fboundp 'set-text-properties)
  320.   "*Non-nil means: use emacs-19 text properties.
  321. Defaults to t if this emacs is capable of handling text properties.")
  322.  
  323. (defvar forms-ro-face 'default
  324.   "The face (a symbol) that is used to display read-only text on the screen.")
  325.  
  326. (defvar forms-rw-face 'region
  327.   "The face (a symbol) that is used to display read-write text on the screen.")
  328.  
  329. ;;; Internal variables.
  330.  
  331. (defvar forms--file-buffer nil
  332.   "Buffer which holds the file data")
  333.  
  334. (defvar forms--total-records 0
  335.   "Total number of records in the data file.")
  336.  
  337. (defvar forms--current-record 0
  338.   "Number of the record currently on the screen.")
  339.  
  340. (defvar forms-mode-map nil
  341.    "Keymap for form buffer.")
  342. (defvar forms-mode-ro-map nil
  343.    "Keymap for form buffer in view mode.")
  344. (defvar forms-mode-edit-map nil
  345.    "Keymap for form buffer in edit mode.")
  346.  
  347. (defvar forms--markers nil
  348.   "Field markers in the screen.")
  349.  
  350. (defvar forms--dyntexts nil
  351.   "Dynamic texts (resulting from function calls) on the screen.")
  352.  
  353. (defvar forms--the-record-list nil 
  354.    "List of strings of the current record, as parsed from the file.")
  355.  
  356. (defvar forms--search-regexp nil
  357.   "Last regexp used by forms-search.")
  358.  
  359. (defvar forms--format nil
  360.   "Formatting routine.")
  361.  
  362. (defvar forms--parser nil
  363.   "Forms parser routine.")
  364.  
  365. (defvar forms--mode-setup nil
  366.   "To keep track of forms-mode being set-up.")
  367. (make-variable-buffer-local 'forms--mode-setup)
  368.  
  369. (defvar forms--dynamic-text nil
  370.   "Array that holds dynamic texts to insert between fields.")
  371.  
  372. (defvar forms--elements nil
  373.   "Array with the order in which the fields are displayed.")
  374.  
  375. (defvar forms--ro-face nil
  376.   "Face used to represent read-only data on the screen.")
  377.  
  378. (defvar forms--rw-face nil
  379.   "Face used to represent read-write data on the screen.")
  380.  
  381. ;;;###autoload 
  382. (defun forms-mode (&optional primary)
  383.   "Major mode to visit files in a field-structured manner using a form.
  384.  
  385. Commands:                        Equivalent keys in read-only mode:
  386.  TAB            forms-next-field          TAB
  387.  \\C-c TAB       forms-next-field          
  388.  \\C-c <         forms-first-record         <
  389.  \\C-c >         forms-last-record          >
  390.  \\C-c ?         describe-mode              ?
  391.  \\C-c \\C-k      forms-delete-record
  392.  \\C-c \\C-q      forms-toggle-read-only     q
  393.  \\C-c \\C-o      forms-insert-record
  394.  \\C-c \\C-l      forms-jump-record          l
  395.  \\C-c \\C-n      forms-next-record          n
  396.  \\C-c \\C-p      forms-prev-record          p
  397.  \\C-c \\C-s      forms-search               s
  398.  \\C-c \\C-x      forms-exit                 x
  399. "
  400.   (interactive)
  401.  
  402.   ;; This is not a simple major mode, as usual.  Therefore, forms-mode
  403.   ;; takes an optional argument `primary' which is used for the
  404.   ;; initial set-up.  Normal use would leave `primary' to nil.
  405.   ;; A global buffer-local variable `forms--mode-setup' has the same
  406.   ;; effect but makes it possible to auto-invoke forms-mode using
  407.   ;; `find-file'.
  408.   ;; Note: although it seems logical to have `make-local-variable'
  409.   ;; executed where the variable is first needed, I have deliberately
  410.   ;; placed all calls in this function.
  411.  
  412.   ;; Primary set-up: evaluate buffer and check if the mandatory
  413.   ;; variables have been set.
  414.   (if (or primary (not forms--mode-setup))
  415.       (progn
  416.     ;;(message "forms: setting up...")
  417.     (kill-all-local-variables)
  418.  
  419.     ;; Make mandatory variables.
  420.     (make-local-variable 'forms-file)
  421.     (make-local-variable 'forms-number-of-fields)
  422.     (make-local-variable 'forms-format-list)
  423.  
  424.     ;; Make optional variables.
  425.     (make-local-variable 'forms-field-sep)
  426.         (make-local-variable 'forms-read-only)
  427.         (make-local-variable 'forms-multi-line)
  428.     (make-local-variable 'forms-forms-scroll)
  429.     (make-local-variable 'forms-forms-jump)
  430.     (make-local-variable 'forms-use-text-properties)
  431.     (make-local-variable 'forms-new-record-filter)
  432.     (make-local-variable 'forms-modified-record-filter)
  433.  
  434.     ;; Make sure no filters exist.
  435.     (setq forms-new-record-filter nil)
  436.     (setq forms-modified-record-filter nil)
  437.  
  438.     ;; If running Emacs 19 under X, setup faces to show read-only and 
  439.     ;; read-write fields.
  440.     (if (fboundp 'make-face)
  441.         (progn
  442.           (make-local-variable 'forms-ro-face)
  443.           (make-local-variable 'forms-rw-face)))
  444.  
  445.     ;; eval the buffer, should set variables
  446.     ;;(message "forms: processing control file...")
  447.     (eval-current-buffer)
  448.  
  449.     ;; check if the mandatory variables make sense.
  450.     (or forms-file
  451.         (error (concat "Forms control file error: " 
  452.                "'forms-file' has not been set")))
  453.     (or forms-number-of-fields
  454.         (error (concat "Forms control file error: "
  455.                "'forms-number-of-fields' has not been set")))
  456.     (or (and (numberp forms-number-of-fields)
  457.          (> forms-number-of-fields 0))
  458.         (error (concat "Forms control file error: "
  459.                "'forms-number-of-fields' must be a number > 0")))
  460.     (or (stringp forms-field-sep)
  461.         (error (concat "Forms control file error: "
  462.                "'forms-field-sep' is not a string")))
  463.     (if forms-multi-line
  464.         (if (and (stringp forms-multi-line)
  465.              (eq (length forms-multi-line) 1))
  466.         (if (string= forms-multi-line forms-field-sep)
  467.             (error (concat "Forms control file error: " 
  468.                    "'forms-multi-line' is equal to 'forms-field-sep'")))
  469.           (error (concat "Forms control file error: "
  470.                  "'forms-multi-line' must be nil or a one-character string"))))
  471.     (or (fboundp 'set-text-properties)
  472.         (setq forms-use-text-properties nil))
  473.         
  474.     ;; Validate and process forms-format-list.
  475.     ;;(message "forms: pre-processing format list...")
  476.     (forms--process-format-list)
  477.  
  478.     ;; Build the formatter and parser.
  479.     ;;(message "forms: building formatter...")
  480.     (make-local-variable 'forms--format)
  481.     (make-local-variable 'forms--markers)
  482.     (make-local-variable 'forms--dyntexts)
  483.     (make-local-variable 'forms--elements)
  484.     ;;(message "forms: building parser...")
  485.     (forms--make-format)
  486.     (make-local-variable 'forms--parser)
  487.     (forms--make-parser)
  488.     ;;(message "forms: building parser... done.")
  489.  
  490.     ;; Check if record filters are defined.
  491.     (if (and forms-new-record-filter
  492.          (not (fboundp forms-new-record-filter)))
  493.         (error (concat "Forms control file error: "
  494.                "'forms-new-record-filter' is not a function")))
  495.  
  496.     (if (and forms-modified-record-filter
  497.          (not (fboundp forms-modified-record-filter)))
  498.         (error (concat "Forms control file error: "
  499.                "'forms-modified-record-filter' is not a function")))
  500.  
  501.     ;; The filters acces the contents of the forms using `forms-fields'.
  502.     (make-local-variable 'forms-fields)
  503.  
  504.     ;; Dynamic text support.
  505.     (make-local-variable 'forms--dynamic-text)
  506.  
  507.     ;; Prevent accidental overwrite of the control file and autosave.
  508.     (setq buffer-file-name nil)
  509.     (auto-save-mode nil)
  510.  
  511.     ;; Prepare this buffer for further processing.
  512.     (setq buffer-read-only nil)
  513.     (erase-buffer)
  514.  
  515.     ;;(message "forms: setting up... done.")
  516.     ))
  517.  
  518.   ;; Copy desired faces to the actual variables used by the forms formatter.
  519.   (if (fboundp 'make-face)
  520.       (progn
  521.     (make-local-variable 'forms--ro-face)
  522.     (make-local-variable 'forms--rw-face)
  523.     (if forms-read-only
  524.         (progn
  525.           (setq forms--ro-face forms-ro-face)
  526.           (setq forms--rw-face forms-ro-face))
  527.       (setq forms--ro-face forms-ro-face)
  528.       (setq forms--rw-face forms-rw-face))))
  529.  
  530.   ;; Make more local variables.
  531.   (make-local-variable 'forms--file-buffer)
  532.   (make-local-variable 'forms--total-records)
  533.   (make-local-variable 'forms--current-record)
  534.   (make-local-variable 'forms--the-record-list)
  535.   (make-local-variable 'forms--search-regexp)
  536.  
  537.   ; The keymaps are global, so multiple forms mode buffers can share them.
  538.   ;(make-local-variable 'forms-mode-map)
  539.   ;(make-local-variable 'forms-mode-ro-map)
  540.   ;(make-local-variable 'forms-mode-edit-map)
  541.   (if forms-mode-map            ; already defined
  542.       nil
  543.     ;;(message "forms: building keymap...")
  544.     (forms--mode-commands)
  545.     ;;(message "forms: building keymap... done.")
  546.     )
  547.  
  548.   ;; find the data file
  549.   (setq forms--file-buffer (find-file-noselect forms-file))
  550.  
  551.   ;; count the number of records, and set see if it may be modified
  552.   (let (ro)
  553.     (setq forms--total-records
  554.       (save-excursion
  555.         (prog1
  556.         (progn
  557.           ;;(message "forms: counting records...")
  558.           (set-buffer forms--file-buffer)
  559.           (bury-buffer (current-buffer))
  560.           (setq ro buffer-read-only)
  561.           (count-lines (point-min) (point-max)))
  562.           ;;(message "forms: counting records... done.")
  563.           )))
  564.     (if ro
  565.     (setq forms-read-only t)))
  566.  
  567.   ;;(message "forms: proceeding setup...")
  568.   ;; set the major mode indicator
  569.   (setq major-mode 'forms-mode)
  570.   (setq mode-name "Forms")
  571.  
  572.   ;; Since we aren't really implementing a minor mode, we hack the modeline
  573.   ;; directly to get the text " View " into forms-read-only form buffers.  For
  574.   ;; that reason, this variable must be buffer only.
  575.   (make-local-variable 'minor-mode-alist)
  576.   (setq minor-mode-alist (list (list 'forms-read-only " View")))
  577.  
  578.   ;;(message "forms: proceeding setup (keymaps)...")
  579.   (forms--set-keymaps)
  580.   ;;(message "forms: proceeding setup (commands)...")
  581.   (forms--change-commands)
  582.  
  583.   ;;(message "forms: proceeding setup (buffer)...")
  584.   (set-buffer-modified-p nil)
  585.  
  586.   ;; setup the first (or current) record to show
  587.   (if (< forms--current-record 1)
  588.       (setq forms--current-record 1))
  589.   (forms-jump-record forms--current-record)
  590.  
  591.   ;; user customising
  592.   ;;(message "forms: proceeding setup (user hooks)...")
  593.   (run-hooks 'forms-mode-hooks)
  594.   ;;(message "forms: setting up... done.")
  595.  
  596.   ;; be helpful
  597.   (forms--help)
  598.  
  599.   ;; initialization done
  600.   (setq forms--mode-setup t))
  601.  
  602. (defun forms--process-format-list ()
  603.   ;; Validate `forms-format-list' and set some global variables.
  604.   ;; Symbols in the list are evaluated, and consecutive strings are
  605.   ;; concatenated.
  606.   ;; Array `forms--elements' is constructed that contains the order
  607.   ;; of the fields on the display. This array is used by 
  608.   ;; `forms--parser-using-text-properties' to extract the fields data
  609.   ;; from the form on the screen.
  610.   ;; Upon completion, `forms-format-list' is garanteed correct, so
  611.   ;; `forms--make-format' and `forms--make-parser' do not need to perform
  612.   ;; any checks.
  613.  
  614.   ;; Verify that `forms-format-list' is not nil.
  615.   (or forms-format-list
  616.       (error (concat "Forms control file error: "
  617.              "'forms-format-list' has not been set")))
  618.   ;; It must be a list.
  619.   (or (listp forms-format-list)
  620.       (error (concat "Forms control file error: "
  621.              "'forms-format-list' is not a list")))
  622.  
  623.   ;; Assume every field is painted once.
  624.   ;; `forms--elements' will grow if needed.
  625.   (setq forms--elements (make-vector forms-number-of-fields nil))
  626.  
  627.   (let ((the-list forms-format-list)    ; the list of format elements
  628.     (this-item 0)            ; element in list
  629.     (prev-item nil)
  630.     (field-num 0))            ; highest field number 
  631.  
  632.     (setq forms-format-list nil)    ; gonna rebuild
  633.  
  634.     (while the-list
  635.  
  636.       (let ((el (car-safe the-list))
  637.         (rem (cdr-safe the-list)))
  638.  
  639.     ;; If it is a symbol, eval it first.
  640.     (if (and (symbolp el)
  641.          (boundp el))
  642.         (setq el (eval el)))
  643.  
  644.     (cond
  645.  
  646.      ;; Try string ...
  647.      ((stringp el)
  648.       (if (stringp prev-item)    ; try to concatenate strings
  649.           (setq prev-item (concat prev-item el))
  650.         (if prev-item
  651.         (setq forms-format-list
  652.               (append forms-format-list (list prev-item) nil)))
  653.         (setq prev-item el)))
  654.  
  655.      ;; Try numeric ...
  656.      ((numberp el) 
  657.  
  658.       ;; Validate range.
  659.       (if (or (<= el 0)
  660.           (> el forms-number-of-fields))
  661.           (error (concat "Forms format error: "
  662.                  "field number %d out of range 1..%d")
  663.              el forms-number-of-fields))
  664.  
  665.       ;; Store forms order.
  666.       (if (> field-num (length forms--elements))
  667.           (setq forms--elements (vconcat forms--elements (1- el)))
  668.         (aset forms--elements field-num (1- el)))
  669.       (setq field-num (1+ field-num))
  670.  
  671.       (if prev-item
  672.           (setq forms-format-list
  673.             (append forms-format-list (list prev-item) nil)))
  674.       (setq prev-item el))
  675.  
  676.      ;; Try function ...
  677.      ((listp el)
  678.  
  679.       ;; Validate.
  680.       (or (fboundp (car-safe el))
  681.           (error (concat "Forms format error: "
  682.                  "not a function "
  683.                  (prin1-to-string (car-safe el)))))
  684.  
  685.       ;; Shift.
  686.       (if prev-item
  687.           (setq forms-format-list
  688.             (append forms-format-list (list prev-item) nil)))
  689.       (setq prev-item el))
  690.  
  691.      ;; else
  692.      (t
  693.       (error (concat "Forms format error: "
  694.              "invalid element "
  695.              (prin1-to-string el)))))
  696.  
  697.     ;; Advance to next element of the list.
  698.     (setq the-list rem)))
  699.  
  700.     ;; Append last item.
  701.     (if prev-item
  702.     (progn
  703.       (setq forms-format-list
  704.         (append forms-format-list (list prev-item) nil))
  705.       ;; Append a newline if the last item is a field.
  706.       ;; This prevents parsing problems.
  707.       ;; Also it makes it possible to insert an empty last field.
  708.       (if (numberp prev-item)
  709.           (setq forms-format-list
  710.             (append forms-format-list (list "\n") nil))))))
  711.  
  712.   (forms--debug 'forms-format-list
  713.         'forms--elements))
  714.  
  715. ;; Special treatment for read-only segments.
  716. ;;
  717. ;; If text is inserted between two read-only segments, it inherits the
  718. ;; read-only properties.  This is not what we want.
  719. ;; To solve this, read-only segments get the `insert-in-front-hooks'
  720. ;; property set with a function that temporarily switches the properties
  721. ;; of the first character of the segment to read-write, so the new
  722. ;; text gets the right properties.
  723. ;; The `post-command-hook' is used to restore the original properties.
  724.  
  725. (defvar forms--iif-start nil
  726.   "Record start of modification command.")
  727. (defvar forms--iif-properties nil
  728.   "Original properties of the character being overridden.")
  729.  
  730. (defun forms--iif-hook (begin end)
  731.   "`insert-in-front-hooks' function for read-only segments."
  732.  
  733.   ;; Note start location.  By making it a marker that points one 
  734.   ;; character beyond the actual location, it is guaranteed to move 
  735.   ;; correctly if text is inserted.
  736.   (or forms--iif-start
  737.       (setq forms--iif-start (copy-marker (1+ (point)))))
  738.  
  739.   ;; Check if there is special treatment required.
  740.   (if (or (<= forms--iif-start 2)
  741.       (get-text-property (- forms--iif-start 2)
  742.                  'read-only))
  743.       (progn
  744.     ;; Fetch current properties.
  745.     (setq forms--iif-properties 
  746.           (text-properties-at (1- forms--iif-start)))
  747.  
  748.     ;; Replace them.
  749.     (let ((inhibit-read-only t))
  750.       (set-text-properties 
  751.        (1- forms--iif-start) forms--iif-start
  752.        (list 'face forms--rw-face 'front-sticky '(face))))
  753.  
  754.     ;; Enable `post-command-hook' to restore the properties.
  755.     (setq post-command-hook
  756.           (append (list 'forms--iif-post-command-hook) post-command-hook)))
  757.  
  758.     ;; No action needed.  Clear marker.
  759.     (setq forms--iif-start nil)))
  760.  
  761. (defun forms--iif-post-command-hook ()
  762.   "`post-command-hook' function for read-only segments."
  763.  
  764.   ;; Disable `post-command-hook'.
  765.   (setq post-command-hook
  766.     (delq 'forms--iif-hook-post-command-hook post-command-hook))
  767.  
  768.   ;; Restore properties.
  769.   (if forms--iif-start
  770.       (let ((inhibit-read-only t))
  771.     (set-text-properties 
  772.      (1- forms--iif-start) forms--iif-start
  773.      forms--iif-properties)))
  774.  
  775.   ;; Cleanup.
  776.   (setq forms--iif-start nil))
  777.  
  778. (defvar forms--marker)
  779. (defvar forms--dyntext)
  780.  
  781. (defun forms--make-format ()
  782.   "Generate `forms--format' using the information in `forms-format-list'."
  783.  
  784.   ;; The real work is done using a mapcar of `forms--make-format-elt' on
  785.   ;; `forms-format-list'.
  786.   ;; This function sets up the necessary environment, and decides
  787.   ;; which function to mapcar.
  788.  
  789.   (let ((forms--marker 0)
  790.     (forms--dyntext 0))
  791.     (setq 
  792.      forms--format
  793.      (if forms-use-text-properties 
  794.      (` (lambda (arg)
  795.           (let ((inhibit-read-only t))
  796.         (,@ (apply 'append
  797.                (mapcar 'forms--make-format-elt-using-text-properties
  798.                    forms-format-list)))
  799.         ;; Prevent insertion before the first text.
  800.         (,@ (if (numberp (car forms-format-list))
  801.             nil
  802.               '((add-text-properties (point-min) (1+ (point-min))
  803.                          '(front-sticky (read-only))))))
  804.         ;; Prevent insertion after the last text.
  805.         (remove-text-properties (1- (point)) (point)
  806.                     '(rear-nonsticky)))
  807.           (setq forms--iif-start nil)))
  808.        (` (lambda (arg)
  809.         (,@ (apply 'append
  810.                (mapcar 'forms--make-format-elt forms-format-list)))))))
  811.  
  812.     ;; We have tallied the number of markers and dynamic texts,
  813.     ;; so we can allocate the arrays now.
  814.     (setq forms--markers (make-vector forms--marker nil))
  815.     (setq forms--dyntexts (make-vector forms--dyntext nil)))
  816.   (forms--debug 'forms--format))
  817.  
  818. (defun forms--make-format-elt-using-text-properties (el)
  819.   "Helper routine to generate format function."
  820.  
  821.   ;; The format routine `forms--format' will look like
  822.   ;;
  823.   ;; ;; preamble
  824.   ;; (lambda (arg)
  825.   ;;   (let ((inhibit-read-only t))
  826.   ;;
  827.   ;;     ;; A string, e.g. "text: ".
  828.   ;;     (set-text-properties 
  829.   ;;      (point)
  830.   ;;      (progn (insert "text: ") (point)) 
  831.   ;;      (list 'face forms--ro-face
  832.   ;;        'read-only 1
  833.   ;;        'insert-in-front-hooks 'forms--iif-hook
  834.   ;;        'rear-nonsticky '(read-only face insert-in-front-hooks)))
  835.   ;;
  836.   ;;     ;; A field, e.g. 6.
  837.   ;;     (let ((here (point)))
  838.   ;;       (aset forms--markers 0 (point-marker))
  839.   ;;       (insert (elt arg 5))
  840.   ;;       (or (= (point) here)
  841.   ;;       (set-text-properties 
  842.   ;;        here (point)
  843.   ;;        (list 'face forms--rw-face
  844.   ;;         'front-sticky '(face))))
  845.   ;;
  846.   ;;     ;; Another string, e.g. "\nmore text: ".
  847.   ;;     (set-text-properties
  848.   ;;      (point)
  849.   ;;      (progn (insert "\nmore text: ") (point))
  850.   ;;      (list 'face forms--ro-face
  851.   ;;        'read-only 2
  852.   ;;        'insert-in-front-hooks 'forms--iif-hook
  853.   ;;        'rear-nonsticky '(read-only face insert-in-front-hooks)))
  854.   ;;
  855.   ;;     ;; A function, e.g. (tocol 40).
  856.   ;;     (set-text-properties
  857.   ;;      (point)
  858.   ;;      (progn
  859.   ;;        (insert (aset forms--dyntexts 0 (tocol 40)))
  860.   ;;        (point))
  861.   ;;      (list 'face forms--ro-face
  862.   ;;        'read-only 2
  863.   ;;        'insert-in-front-hooks 'forms--iif-hook
  864.   ;;        'rear-nonsticky '(read-only face insert-in-front-hooks)))
  865.   ;;
  866.   ;;     ;; Prevent insertion before the first text.
  867.   ;;     (add-text-properties (point-min) (1+ (point-min))
  868.   ;;                  '(front-sticky (read-only))))))
  869.   ;;     ;; Prevent insertion after the last text.
  870.   ;;     (remove-text-properties (1- (point)) (point)
  871.   ;;                  '(rear-nonsticky)))
  872.   ;;
  873.   ;;     ;; wrap up
  874.   ;;     (setq forms--iif-start nil)
  875.   ;;     ))
  876.  
  877.   (cond
  878.    ((stringp el)
  879.     
  880.     (` ((set-text-properties 
  881.      (point)            ; start at point
  882.      (progn                ; until after insertion
  883.        (insert (, el))
  884.        (point))
  885.      (list 'face forms--ro-face    ; read-only appearance
  886.            'read-only (,@ (list (1+ forms--marker)))
  887.            'insert-in-front-hooks '(forms--iif-hook)
  888.            'rear-nonsticky '(face read-only insert-in-front-hooks))))))
  889.     
  890.    ((numberp el)
  891.     (` ((let ((here (point)))
  892.       (aset forms--markers 
  893.         (, (prog1 forms--marker
  894.              (setq forms--marker (1+ forms--marker))))
  895.         (point-marker))
  896.       (insert (elt arg (, (1- el))))
  897.       (or (= (point) here)
  898.           (set-text-properties 
  899.            here (point)
  900.            (list 'face forms--rw-face
  901.              'front-sticky '(face))))))))
  902.  
  903.    ((listp el)
  904.     (` ((set-text-properties
  905.      (point)
  906.      (progn
  907.        (insert (aset forms--dyntexts 
  908.              (, (prog1 forms--dyntext
  909.                   (setq forms--dyntext (1+ forms--dyntext))))
  910.              (, el)))
  911.        (point))
  912.      (list 'face forms--ro-face
  913.            'read-only (,@ (list (1+ forms--marker)))
  914.            'insert-in-front-hooks '(forms--iif-hook)
  915.            'rear-nonsticky '(read-only face insert-in-front-hooks))))))
  916.  
  917.    ;; end of cond
  918.    ))
  919.  
  920. (defun forms--make-format-elt (el)
  921.   "Helper routine to generate format function."
  922.  
  923.   ;; If we're not using text properties, the format routine
  924.   ;; `forms--format' will look like
  925.   ;;
  926.   ;; (lambda (arg)
  927.   ;;   ;; a string, e.g. "text: "
  928.   ;;   (insert "text: ")
  929.   ;;   ;; a field, e.g. 6
  930.   ;;   (aset forms--markers 0 (point-marker))
  931.   ;;   (insert (elt arg 5))
  932.   ;;   ;; another string, e.g. "\nmore text: "
  933.   ;;   (insert "\nmore text: ")
  934.   ;;   ;; a function, e.g. (tocol 40)
  935.   ;;   (insert (aset forms--dyntexts 0 (tocol 40)))
  936.   ;;   ... )
  937.  
  938.   (cond 
  939.    ((stringp el)
  940.     (` ((insert (, el)))))
  941.    ((numberp el)
  942.     (prog1
  943.     (` ((aset forms--markers (, forms--marker) (point-marker))
  944.         (insert (elt arg (, (1- el))))))
  945.       (setq forms--marker (1+ forms--marker))))
  946.    ((listp el)
  947.     (prog1
  948.     (` ((insert (aset forms--dyntexts (, forms--dyntext) (, el)))))
  949.       (setq forms--dyntext (1+ forms--dyntext))))))
  950.  
  951. (defvar forms--field)
  952. (defvar forms--recordv)
  953. (defvar forms--seen-text)
  954.  
  955. (defun forms--make-parser ()
  956.   "Generate `forms--parser' from the information in `forms-format-list'."
  957.  
  958.   ;; If we can use text properties, we simply set it to
  959.   ;; `forms--parser-using-text-properties'.
  960.   ;; Otherwise, the function is constructed using a mapcar of
  961.   ;; `forms--make-parser-elt on `forms-format-list'.
  962.  
  963.   (setq
  964.    forms--parser
  965.    (if forms-use-text-properties
  966.        (function forms--parser-using-text-properties)
  967.      (let ((forms--field nil)
  968.        (forms--seen-text nil)
  969.        (forms--dyntext 0))
  970.  
  971.        ;; Note: we add a nil element to the list passed to `mapcar',
  972.        ;; see `forms--make-parser-elt' for details.
  973.        (` (lambda nil
  974.         (let (here)
  975.           (goto-char (point-min))
  976.           (,@ (apply 'append
  977.              (mapcar 
  978.               'forms--make-parser-elt 
  979.               (append forms-format-list (list nil)))))))))))
  980.  
  981.   (forms--debug 'forms--parser))
  982.  
  983. (defun forms--parser-using-text-properties ()
  984.   "Extract field info from forms when using text properties."
  985.  
  986.   ;; Using text properties, we can simply jump to the markers, and
  987.   ;; extract the information up to the following read-only segment.
  988.  
  989.   (let ((i 0)
  990.     here there)
  991.     (while (< i (length forms--markers))
  992.       (goto-char (setq here (aref forms--markers i)))
  993.       (if (get-text-property here 'read-only)
  994.       (aset forms--recordv (aref forms--elements i) nil)
  995.     (if (setq there 
  996.           (next-single-property-change here 'read-only))
  997.         (aset forms--recordv (aref forms--elements i)
  998.           (buffer-substring here there))
  999.       (aset forms--recordv (aref forms--elements i)
  1000.         (buffer-substring here (point-max)))))
  1001.       (setq i (1+ i)))))
  1002.  
  1003. (defun forms--make-parser-elt (el)
  1004.   "Helper routine to generate forms parser function."
  1005.  
  1006.   ;; The parse routine will look like:
  1007.   ;;
  1008.   ;; (lambda nil
  1009.   ;;   (let (here)
  1010.   ;;     (goto-char (point-min))
  1011.   ;; 
  1012.   ;;     ;;  "text: "
  1013.   ;;     (if (not (looking-at "text: "))
  1014.   ;;         (error "Parse error: cannot find \"text: \""))
  1015.   ;;     (forward-char 6)    ; past "text: "
  1016.   ;; 
  1017.   ;;     ;;  6
  1018.   ;;     ;;  "\nmore text: "
  1019.   ;;     (setq here (point))
  1020.   ;;     (if (not (search-forward "\nmore text: " nil t nil))
  1021.   ;;         (error "Parse error: cannot find \"\\nmore text: \""))
  1022.   ;;     (aset forms--recordv 5 (buffer-substring here (- (point) 12)))
  1023.   ;;
  1024.   ;;     ;;  (tocol 40)
  1025.   ;;    (let ((forms--dyntext (car-safe forms--dynamic-text)))
  1026.   ;;      (if (not (looking-at (regexp-quote forms--dyntext)))
  1027.   ;;          (error "Parse error: not looking at \"%s\"" forms--dyntext))
  1028.   ;;      (forward-char (length forms--dyntext))
  1029.   ;;      (setq forms--dynamic-text (cdr-safe forms--dynamic-text)))
  1030.   ;;     ... 
  1031.   ;;     ;; final flush (due to terminator sentinel, see below)
  1032.   ;;    (aset forms--recordv 7 (buffer-substring (point) (point-max)))
  1033.  
  1034.   (cond
  1035.    ((stringp el)
  1036.     (prog1
  1037.     (if forms--field
  1038.         (` ((setq here (point))
  1039.         (if (not (search-forward (, el) nil t nil))
  1040.             (error "Parse error: cannot find \"%s\"" (, el)))
  1041.         (aset forms--recordv (, (1- forms--field))
  1042.               (buffer-substring here
  1043.                     (- (point) (, (length el)))))))
  1044.       (` ((if (not (looking-at (, (regexp-quote el))))
  1045.           (error "Parse error: not looking at \"%s\"" (, el)))
  1046.           (forward-char (, (length el))))))
  1047.       (setq forms--seen-text t)
  1048.       (setq forms--field nil)))
  1049.    ((numberp el)
  1050.     (if forms--field
  1051.     (error "Cannot parse adjacent fields %d and %d"
  1052.            forms--field el)
  1053.       (setq forms--field el)
  1054.       nil))
  1055.    ((null el)
  1056.     (if forms--field
  1057.     (` ((aset forms--recordv (, (1- forms--field))
  1058.           (buffer-substring (point) (point-max)))))))
  1059.    ((listp el)
  1060.     (prog1
  1061.     (if forms--field
  1062.         (` ((let ((here (point))
  1063.               (forms--dyntext (aref forms--dyntexts (, forms--dyntext))))
  1064.           (if (not (search-forward forms--dyntext nil t nil))
  1065.               (error "Parse error: cannot find \"%s\"" forms--dyntext))
  1066.           (aset forms--recordv (, (1- forms--field))
  1067.             (buffer-substring here
  1068.                       (- (point) (length forms--dyntext)))))))
  1069.       (` ((let ((forms--dyntext (aref forms--dyntexts (, forms--dyntext))))
  1070.         (if (not (looking-at (regexp-quote forms--dyntext)))
  1071.             (error "Parse error: not looking at \"%s\"" forms--dyntext))
  1072.         (forward-char (length forms--dyntext))))))
  1073.       (setq forms--dyntext (1+ forms--dyntext))
  1074.       (setq forms--seen-text t)
  1075.       (setq forms--field nil)))
  1076.    ))
  1077.  
  1078. (defun forms--set-keymaps ()
  1079.   "Set the keymaps used in this mode."
  1080.  
  1081.   (use-local-map (if forms-read-only 
  1082.              forms-mode-ro-map 
  1083.            forms-mode-edit-map)))
  1084.  
  1085. (defun forms--mode-commands ()
  1086.   "Fill the Forms mode keymaps."
  1087.  
  1088.   ;; `forms-mode-map' is always accessible via \C-c prefix.
  1089.   (setq forms-mode-map (make-keymap))
  1090.   (define-key forms-mode-map "\t" 'forms-next-field)
  1091.   (define-key forms-mode-map "\C-k" 'forms-delete-record)
  1092.   (define-key forms-mode-map "\C-q" 'forms-toggle-read-only)
  1093.   (define-key forms-mode-map "\C-o" 'forms-insert-record)
  1094.   (define-key forms-mode-map "\C-l" 'forms-jump-record)
  1095.   (define-key forms-mode-map "\C-n" 'forms-next-record)
  1096.   (define-key forms-mode-map "\C-p" 'forms-prev-record)
  1097.   (define-key forms-mode-map "\C-s" 'forms-search)
  1098.   (define-key forms-mode-map "\C-x" 'forms-exit)
  1099.   (define-key forms-mode-map "<" 'forms-first-record)
  1100.   (define-key forms-mode-map ">" 'forms-last-record)
  1101.   (define-key forms-mode-map "?" 'describe-mode)
  1102.   (define-key forms-mode-map "\C-?" 'forms-prev-record)
  1103.  
  1104.   ;; `forms-mode-ro-map' replaces the local map when in read-only mode.
  1105.   (setq forms-mode-ro-map (make-keymap))
  1106.   (suppress-keymap forms-mode-ro-map)
  1107.   (define-key forms-mode-ro-map "\C-c" forms-mode-map)
  1108.   (define-key forms-mode-ro-map "\t" 'forms-next-field)
  1109.   (define-key forms-mode-ro-map "q" 'forms-toggle-read-only)
  1110.   (define-key forms-mode-ro-map "l" 'forms-jump-record)
  1111.   (define-key forms-mode-ro-map "n" 'forms-next-record)
  1112.   (define-key forms-mode-ro-map "p" 'forms-prev-record)
  1113.   (define-key forms-mode-ro-map "s" 'forms-search)
  1114.   (define-key forms-mode-ro-map "x" 'forms-exit)
  1115.   (define-key forms-mode-ro-map "<" 'forms-first-record)
  1116.   (define-key forms-mode-ro-map ">" 'forms-last-record)
  1117.   (define-key forms-mode-ro-map "?" 'describe-mode)
  1118.   (define-key forms-mode-ro-map " " 'forms-next-record)
  1119.   (forms--mode-commands1 forms-mode-ro-map)
  1120.  
  1121.   ;; This is the normal, local map.
  1122.   (setq forms-mode-edit-map (make-keymap))
  1123.   (define-key forms-mode-edit-map "\t"   'forms-next-field)
  1124.   (define-key forms-mode-edit-map "\C-c" forms-mode-map)
  1125.   (forms--mode-commands1 forms-mode-edit-map)
  1126.   )
  1127.  
  1128. (defun forms--mode-commands1 (map)
  1129.   "Helper routine to define keys."
  1130.   (define-key map [TAB] 'forms-next-field)
  1131.   (define-key map [S-tab] 'forms-prev-field)
  1132.   (define-key map [next] 'forms-next-record)
  1133.   (define-key map [prior] 'forms-prev-record)
  1134.   (define-key map [begin] 'forms-first-record)
  1135.   (define-key map [last] 'forms-last-record)
  1136.   (define-key map [backtab] 'forms-prev-field)
  1137.   )
  1138.  
  1139. ;;; Changed functions
  1140.  
  1141. (defun forms--change-commands ()
  1142.   "Localize some commands for Forms mode."
  1143.  
  1144.   ;; scroll-down -> forms-prev-record
  1145.   ;; scroll-up -> forms-next-record
  1146.   (if forms-forms-scroll
  1147.       (progn
  1148.     (substitute-key-definition 'scroll-up 'forms-next-record
  1149.                    (current-local-map)
  1150.                    (current-global-map))
  1151.     (substitute-key-definition 'scroll-down 'forms-prev-record
  1152.                    (current-local-map)
  1153.                    (current-global-map))))
  1154.   ;;
  1155.   ;; beginning-of-buffer -> forms-first-record
  1156.   ;; end-of-buffer -> forms-end-record
  1157.   (if forms-forms-jump
  1158.       (progn
  1159.     (substitute-key-definition 'beginning-of-buffer 'forms-first-record
  1160.                    (current-local-map)
  1161.                    (current-global-map))
  1162.     (substitute-key-definition 'end-of-buffer 'forms-last-record
  1163.                    (current-local-map)
  1164.                    (current-global-map))))
  1165.   ;;
  1166.   ;; save-buffer -> forms--save-buffer
  1167.   (make-local-variable 'local-write-file-hooks)
  1168.   (add-hook 'local-write-file-hooks
  1169.         (function
  1170.          (lambda (nil)
  1171.            (forms--checkmod)
  1172.            (save-excursion
  1173.          (set-buffer forms--file-buffer)
  1174.          (save-buffer))
  1175.            t)))
  1176.   ;; We have our own revert function - use it
  1177.   (make-local-variable 'revert-buffer-function)
  1178.   (setq revert-buffer-function 'forms-revert-buffer)
  1179.  
  1180.   t)
  1181.  
  1182. (defun forms--help ()
  1183.   "Initial help for Forms mode."
  1184.   ;; We should use
  1185.   (message (substitute-command-keys (concat
  1186.   "\\[forms-next-record]:next"
  1187.   "   \\[forms-prev-record]:prev"
  1188.   "   \\[forms-first-record]:first"
  1189.   "   \\[forms-last-record]:last"
  1190.   "   \\[describe-mode]:help"))))
  1191.   ; but it's too slow ....
  1192. ;  (if forms-read-only
  1193. ;      (message "SPC:next   DEL:prev   <:first   >:last   ?:help   q:exit")
  1194. ;    (message "C-c n:next   C-c p:prev   C-c <:first   C-c >:last   C-c ?:help   C-c q:exit"))
  1195. ;  )
  1196.  
  1197. (defun forms--trans (subj arg rep)
  1198.   "Translate in SUBJ all chars ARG into char REP.  ARG and REP should
  1199.  be single-char strings."
  1200.   (let ((i 0)
  1201.     (x (length subj))
  1202.     (re (regexp-quote arg))
  1203.     (k (string-to-char rep)))
  1204.     (while (setq i (string-match re subj i))
  1205.       (aset subj i k)
  1206.       (setq i (1+ i)))))
  1207.  
  1208. (defun forms--exit (query &optional save)
  1209.   "Internal exit from forms mode function."
  1210.  
  1211.   (let ((buf (buffer-name forms--file-buffer)))
  1212.     (forms--checkmod)
  1213.     (if (and save
  1214.          (buffer-modified-p forms--file-buffer))
  1215.     (save-excursion
  1216.       (set-buffer forms--file-buffer)
  1217.       (save-buffer)))
  1218.     (save-excursion
  1219.       (set-buffer forms--file-buffer)
  1220.       (delete-auto-save-file-if-necessary)
  1221.       (kill-buffer (current-buffer)))
  1222.     (if (get-buffer buf)    ; not killed???
  1223.       (if save
  1224.       (progn
  1225.         (beep)
  1226.         (message "Problem saving buffers?")))
  1227.       (delete-auto-save-file-if-necessary)
  1228.       (kill-buffer (current-buffer)))))
  1229.  
  1230. (defun forms--get-record ()
  1231.   "Fetch the current record from the file buffer."
  1232.  
  1233.   ;; This function is executed in the context of the `forms--file-buffer'.
  1234.  
  1235.   (or (bolp)
  1236.       (beginning-of-line nil))
  1237.   (let ((here (point)))
  1238.     (prog2
  1239.      (end-of-line)
  1240.      (buffer-substring here (point))
  1241.      (goto-char here))))
  1242.  
  1243. (defun forms--show-record (the-record)
  1244.   "Format THE-RECORD and display it in the current buffer."
  1245.  
  1246.   ;; Split the-record.
  1247.   (let (the-result
  1248.     (start-pos 0)
  1249.     found-pos
  1250.     (field-sep-length (length forms-field-sep)))
  1251.     (if forms-multi-line
  1252.     (forms--trans the-record forms-multi-line "\n"))
  1253.     ;; Add an extra separator (makes splitting easy).
  1254.     (setq the-record (concat the-record forms-field-sep))
  1255.     (while (setq found-pos (string-match forms-field-sep the-record start-pos))
  1256.       (let ((ent (substring the-record start-pos found-pos)))
  1257.     (setq the-result
  1258.           (append the-result (list ent)))
  1259.     (setq start-pos (+ field-sep-length found-pos))))
  1260.     (setq forms--the-record-list the-result))
  1261.  
  1262.   (setq buffer-read-only nil)
  1263.   (if forms-use-text-properties
  1264.       (let ((inhibit-read-only t))
  1265.     (set-text-properties (point-min) (point-max) nil)))
  1266.   (erase-buffer)
  1267.  
  1268.   ;; Verify the number of fields, extend forms--the-record-list if needed.
  1269.   (if (= (length forms--the-record-list) forms-number-of-fields)
  1270.       nil
  1271.     (beep)
  1272.     (message "Warning: this record has %d fields instead of %d"
  1273.          (length forms--the-record-list) forms-number-of-fields)
  1274.     (if (< (length forms--the-record-list) forms-number-of-fields)
  1275.     (setq forms--the-record-list 
  1276.           (append forms--the-record-list
  1277.               (make-list 
  1278.                (- forms-number-of-fields 
  1279.               (length forms--the-record-list))
  1280.                "")))))
  1281.  
  1282.   ;; Call the formatter function.
  1283.   (setq forms-fields (append (list nil) forms--the-record-list nil))
  1284.   (funcall forms--format forms--the-record-list)
  1285.  
  1286.   ;; Prepare.
  1287.   (goto-char (point-min))
  1288.   (set-buffer-modified-p nil)
  1289.   (setq buffer-read-only forms-read-only)
  1290.   (setq mode-line-process
  1291.     (concat " " forms--current-record "/" forms--total-records)))
  1292.  
  1293. (defun forms--parse-form ()
  1294.   "Parse contents of form into list of strings."
  1295.   ;; The contents of the form are parsed, and a new list of strings
  1296.   ;; is constructed.
  1297.   ;; A vector with the strings from the original record is 
  1298.   ;; constructed, which is updated with the new contents.  Therefore
  1299.   ;; fields which were not in the form are not modified.
  1300.   ;; Finally, the vector is transformed into a list for further processing.
  1301.  
  1302.   (let (forms--recordv)
  1303.  
  1304.     ;; Build the vector.
  1305.     (setq forms--recordv (vconcat forms--the-record-list))
  1306.  
  1307.     ;; Parse the form and update the vector.
  1308.     (let ((forms--dynamic-text forms--dynamic-text))
  1309.       (funcall forms--parser))
  1310.  
  1311.     (if forms-modified-record-filter
  1312.     ;; As a service to the user, we add a zeroth element so she
  1313.     ;; can use the same indices as in the forms definition.
  1314.     (let ((the-fields (vconcat [nil] forms--recordv)))
  1315.       (setq the-fields (funcall forms-modified-record-filter the-fields))
  1316.       (cdr (append the-fields nil)))
  1317.  
  1318.       ;; Transform to a list and return.
  1319.       (append forms--recordv nil))))
  1320.  
  1321. (defun forms--update ()
  1322.   "Update current record with contents of form.
  1323. As a side effect: sets `forms--the-record-list'."
  1324.  
  1325.   (if forms-read-only
  1326.       (progn
  1327.     (message "Read-only buffer!")
  1328.     (beep))
  1329.  
  1330.     (let (the-record)
  1331.       ;; Build new record.
  1332.       (setq forms--the-record-list (forms--parse-form))
  1333.       (setq the-record
  1334.         (mapconcat 'identity forms--the-record-list forms-field-sep))
  1335.  
  1336.       ;; Handle multi-line fields, if allowed.
  1337.       (if forms-multi-line
  1338.       (forms--trans the-record "\n" forms-multi-line))
  1339.  
  1340.       ;; A final sanity check before updating.
  1341.       (if (string-match "\n" the-record)
  1342.       (progn
  1343.         (message "Multi-line fields in this record - update refused!")
  1344.         (beep))
  1345.  
  1346.     (save-excursion
  1347.       (set-buffer forms--file-buffer)
  1348.       ;; Use delete-region instead of kill-region, to avoid
  1349.       ;; adding junk to the kill-ring.
  1350.       (delete-region (save-excursion (beginning-of-line) (point))
  1351.              (save-excursion (end-of-line) (point)))
  1352.       (insert the-record)
  1353.       (beginning-of-line))))))
  1354.  
  1355. (defun forms--checkmod ()
  1356.   "Check if this form has been modified, and call forms--update if so."
  1357.   (if (buffer-modified-p nil)
  1358.       (let ((here (point)))
  1359.     (forms--update)
  1360.     (set-buffer-modified-p nil)
  1361.     (goto-char here))))
  1362.  
  1363. ;;; Start and exit
  1364.  
  1365. ;;;###autoload
  1366. (defun forms-find-file (fn)
  1367.   "Visit a file in Forms mode."
  1368.   (interactive "fForms file: ")
  1369.   (find-file-read-only fn)
  1370.   (or forms--mode-setup (forms-mode t)))
  1371.  
  1372. ;;;###autoload
  1373. (defun forms-find-file-other-window (fn)
  1374.   "Visit a file in Forms mode in other window."
  1375.   (interactive "fFbrowse file in other window: ")
  1376.   (find-file-other-window fn)
  1377.   (eval-current-buffer)
  1378.   (or forms--mode-setup (forms-mode t)))
  1379.  
  1380. (defun forms-exit (query)
  1381.   "Normal exit from Forms mode.  Modified buffers are saved."
  1382.   (interactive "P")
  1383.   (forms--exit query t))
  1384.  
  1385. (defun forms-exit-no-save (query)
  1386.   "Exit from Forms mode without saving buffers."
  1387.   (interactive "P")
  1388.   (forms--exit query nil))
  1389.  
  1390. ;;; Navigating commands
  1391.  
  1392. (defun forms-next-record (arg)
  1393.   "Advance to the ARGth following record."
  1394.   (interactive "P")
  1395.   (forms-jump-record (+ forms--current-record (prefix-numeric-value arg)) t))
  1396.  
  1397. (defun forms-prev-record (arg)
  1398.   "Advance to the ARGth previous record."
  1399.   (interactive "P")
  1400.   (forms-jump-record (- forms--current-record (prefix-numeric-value arg)) t))
  1401.  
  1402. (defun forms-jump-record (arg &optional relative)
  1403.   "Jump to a random record."
  1404.   (interactive "NRecord number: ")
  1405.  
  1406.   ;; Verify that the record number is within range.
  1407.   (if (or (> arg forms--total-records)
  1408.       (<= arg 0))
  1409.     (progn
  1410.       (beep)
  1411.       ;; Don't give the message if just paging.
  1412.       (if (not relative)
  1413.       (message "Record number %d out of range 1..%d"
  1414.            arg forms--total-records))
  1415.       )
  1416.  
  1417.     ;; Flush.
  1418.     (forms--checkmod)
  1419.  
  1420.     ;; Calculate displacement.
  1421.     (let ((disp (- arg forms--current-record))
  1422.       (cur forms--current-record))
  1423.  
  1424.       ;; `forms--show-record' needs it now.
  1425.       (setq forms--current-record arg)
  1426.  
  1427.       ;; Get the record and show it.
  1428.       (forms--show-record
  1429.        (save-excursion
  1430.      (set-buffer forms--file-buffer)
  1431.      (beginning-of-line)
  1432.  
  1433.      ;; Move, and adjust the amount if needed (shouldn't happen).
  1434.      (if relative
  1435.          (if (zerop disp)
  1436.          nil
  1437.            (setq cur (+ cur disp (- (forward-line disp)))))
  1438.        (setq cur (+ cur disp (- (goto-line arg)))))
  1439.  
  1440.      (forms--get-record)))
  1441.  
  1442.       ;; This shouldn't happen.
  1443.       (if (/= forms--current-record cur)
  1444.       (progn
  1445.         (setq forms--current-record cur)
  1446.         (beep)
  1447.         (message "Stuck at record %d" cur))))))
  1448.  
  1449. (defun forms-first-record ()
  1450.   "Jump to first record."
  1451.   (interactive)
  1452.   (forms-jump-record 1))
  1453.  
  1454. (defun forms-last-record ()
  1455.   "Jump to last record.
  1456. As a side effect: re-calculates the number of records in the data file."
  1457.   (interactive)
  1458.   (let
  1459.       ((numrec 
  1460.     (save-excursion
  1461.       (set-buffer forms--file-buffer)
  1462.       (count-lines (point-min) (point-max)))))
  1463.     (if (= numrec forms--total-records)
  1464.     nil
  1465.       (beep)
  1466.       (setq forms--total-records numrec)
  1467.       (message "Warning: number of records changed to %d" forms--total-records)))
  1468.   (forms-jump-record forms--total-records))
  1469.  
  1470. ;;; Other commands
  1471.  
  1472. (defun forms-toggle-read-only (arg)
  1473.   "Toggles read-only mode of a forms mode buffer.
  1474. With an argument, enables read-only mode if the argument is positive.
  1475. Otherwise enables edit mode if the visited file is writeable."
  1476.  
  1477.   (interactive "P")
  1478.  
  1479.   (if (if arg
  1480.       ;; Negative arg means switch it off.
  1481.       (<= (prefix-numeric-value arg) 0)
  1482.     ;; No arg means toggle.
  1483.     forms-read-only)
  1484.  
  1485.       ;; Enable edit mode, if possible.
  1486.       (let ((ro forms-read-only))
  1487.     (if (save-excursion
  1488.           (set-buffer forms--file-buffer)
  1489.           buffer-read-only)
  1490.         (progn
  1491.           (setq forms-read-only t)
  1492.           (message "No write access to \"%s\"" forms-file)
  1493.           (beep))
  1494.       (setq forms-read-only nil))
  1495.     (if (equal ro forms-read-only)
  1496.         nil
  1497.       (forms-mode)))
  1498.  
  1499.     ;; Enable view mode.
  1500.     (if forms-read-only
  1501.     nil
  1502.       (forms--checkmod)            ; sync
  1503.       (setq forms-read-only t)
  1504.       (forms-mode))))
  1505.  
  1506. ;; Sample:
  1507. ;; (defun my-new-record-filter (the-fields)
  1508. ;;   ;; numbers are relative to 1
  1509. ;;   (aset the-fields 4 (current-time-string))
  1510. ;;   (aset the-fields 6 (user-login-name))
  1511. ;;   the-list)
  1512. ;; (setq forms-new-record-filter 'my-new-record-filter)
  1513.  
  1514. (defun forms-insert-record (arg)
  1515.   "Create a new record before the current one.
  1516. With ARG: store the record after the current one.
  1517. If `forms-new-record-filter' contains the name of a function, 
  1518. it is called to fill (some of) the fields with default values."
  1519.  
  1520.   (interactive "P")
  1521.  
  1522.   (if forms-read-only
  1523.       (error ""))
  1524.  
  1525.   (let ((ln (if arg (1+ forms--current-record) forms--current-record))
  1526.         the-list the-record)
  1527.  
  1528.     (forms--checkmod)
  1529.     (if forms-new-record-filter
  1530.     ;; As a service to the user, we add a zeroth element so she
  1531.     ;; can use the same indices as in the forms definition.
  1532.     (let ((the-fields (make-vector (1+ forms-number-of-fields) "")))
  1533.       (setq the-fields (funcall forms-new-record-filter the-fields))
  1534.       (setq the-list (cdr (append the-fields nil))))
  1535.       (setq the-list (make-list forms-number-of-fields "")))
  1536.  
  1537.     (setq the-record
  1538.       (mapconcat
  1539.       'identity
  1540.       the-list
  1541.       forms-field-sep))
  1542.  
  1543.     (save-excursion
  1544.       (set-buffer forms--file-buffer)
  1545.       (goto-line ln)
  1546.       (open-line 1)
  1547.       (insert the-record)
  1548.       (beginning-of-line))
  1549.     
  1550.     (setq forms--current-record ln))
  1551.  
  1552.   (setq forms--total-records (1+ forms--total-records))
  1553.   (forms-jump-record forms--current-record))
  1554.  
  1555. (defun forms-delete-record (arg)
  1556.   "Deletes a record.  With a prefix argument: don't ask."
  1557.   (interactive "P")
  1558.  
  1559.   (if forms-read-only
  1560.       (error ""))
  1561.  
  1562.   (forms--checkmod)
  1563.   (if (or arg
  1564.       (y-or-n-p "Really delete this record? "))
  1565.       (let ((ln forms--current-record))
  1566.     (save-excursion
  1567.       (set-buffer forms--file-buffer)
  1568.       (goto-line ln)
  1569.       ;; Use delete-region instead of kill-region, to avoid
  1570.       ;; adding junk to the kill-ring.
  1571.       (delete-region (save-excursion (beginning-of-line) (point))
  1572.              (save-excursion (end-of-line) (1+ (point)))))
  1573.     (setq forms--total-records (1- forms--total-records))
  1574.     (if (> forms--current-record forms--total-records)
  1575.         (setq forms--current-record forms--total-records))
  1576.     (forms-jump-record forms--current-record)))
  1577.   (message ""))
  1578.  
  1579. (defun forms-search (regexp)
  1580.   "Search REGEXP in file buffer."
  1581.   (interactive 
  1582.    (list (read-string (concat "Search for" 
  1583.                   (if forms--search-regexp
  1584.                    (concat " ("
  1585.                        forms--search-regexp
  1586.                        ")"))
  1587.                   ": "))))
  1588.   (if (equal "" regexp)
  1589.       (setq regexp forms--search-regexp))
  1590.   (forms--checkmod)
  1591.  
  1592.   (let (the-line the-record here
  1593.          (fld-sep forms-field-sep))
  1594.     (if (save-excursion
  1595.       (set-buffer forms--file-buffer)
  1596.       (setq here (point))
  1597.       (end-of-line)
  1598.       (if (null (re-search-forward regexp nil t))
  1599.           (progn
  1600.         (goto-char here)
  1601.         (message (concat "\"" regexp "\" not found."))
  1602.         nil)
  1603.         (setq the-record (forms--get-record))
  1604.         (setq the-line (1+ (count-lines (point-min) (point))))))
  1605.     (progn
  1606.       (setq forms--current-record the-line)
  1607.       (forms--show-record the-record)
  1608.       (re-search-forward regexp nil t))))
  1609.   (setq forms--search-regexp regexp))
  1610.  
  1611. (defun forms-revert-buffer (&optional arg noconfirm)
  1612.   "Reverts current form to un-modified."
  1613.   (interactive "P")
  1614.   (if (or noconfirm
  1615.       (yes-or-no-p "Revert form to unmodified? "))
  1616.       (progn
  1617.     (set-buffer-modified-p nil)
  1618.     (forms-jump-record forms--current-record))))
  1619.  
  1620. (defun forms-next-field (arg)
  1621.   "Jump to ARG-th next field."
  1622.   (interactive "p")
  1623.  
  1624.   (let ((i 0)
  1625.     (here (point))
  1626.     there
  1627.     (cnt 0))
  1628.  
  1629.     (if (zerop arg)
  1630.     (setq cnt 1)
  1631.       (setq cnt (+ cnt arg)))
  1632.  
  1633.     (if (catch 'done
  1634.       (while (< i (length forms--markers))
  1635.         (if (or (null (setq there (aref forms--markers i)))
  1636.             (<= there here))
  1637.         nil
  1638.           (if (<= (setq cnt (1- cnt)) 0)
  1639.           (progn
  1640.             (goto-char there)
  1641.             (throw 'done t))))
  1642.         (setq i (1+ i))))
  1643.     nil
  1644.       (goto-char (aref forms--markers 0)))))
  1645.  
  1646. (defun forms-prev-field (arg)
  1647.   "Jump to ARG-th previous field."
  1648.   (interactive "p")
  1649.  
  1650.   (let ((i (length forms--markers))
  1651.     (here (point))
  1652.     there
  1653.     (cnt 0))
  1654.  
  1655.     (if (zerop arg)
  1656.     (setq cnt 1)
  1657.       (setq cnt (+ cnt arg)))
  1658.  
  1659.     (if (catch 'done
  1660.       (while (> i 0)
  1661.         (setq i ( 1- i))
  1662.         (if (or (null (setq there (aref forms--markers i)))
  1663.             (>= there here))
  1664.         nil
  1665.           (if (<= (setq cnt (1- cnt)) 0)
  1666.           (progn
  1667.             (goto-char there)
  1668.             (throw 'done t))))))
  1669.     nil
  1670.       (goto-char (aref forms--markers (1- (length forms--markers)))))))
  1671. ;;;
  1672. ;;; Special service
  1673. ;;;
  1674. (defun forms-enumerate (the-fields)
  1675.   "Take a quoted list of symbols, and set their values to sequential numbers.
  1676. The first symbol gets number 1, the second 2 and so on.
  1677. It returns the higest number.
  1678.  
  1679. Usage: (setq forms-number-of-fields
  1680.              (forms-enumerate
  1681.               '(field1 field2 field2 ...)))"
  1682.  
  1683.   (let ((the-index 0))
  1684.     (while the-fields
  1685.       (setq the-index (1+ the-index))
  1686.       (let ((el (car-safe the-fields)))
  1687.     (setq the-fields (cdr-safe the-fields))
  1688.     (set el the-index)))
  1689.     the-index))
  1690.  
  1691. ;;; Debugging
  1692.  
  1693. (defvar forms--debug nil
  1694.   "*Enables forms-mode debugging if not nil.")
  1695.  
  1696. (defun forms--debug (&rest args)
  1697.   "Internal debugging routine."
  1698.   (if forms--debug
  1699.       (let ((ret nil))
  1700.     (while args
  1701.       (let ((el (car-safe args)))
  1702.         (setq args (cdr-safe args))
  1703.         (if (stringp el)
  1704.         (setq ret (concat ret el))
  1705.           (setq ret (concat ret (prin1-to-string el) " = "))
  1706.           (if (boundp el)
  1707.           (let ((vel (eval el)))
  1708.             (setq ret (concat ret (prin1-to-string vel) "\n")))
  1709.         (setq ret (concat ret "<unbound>" "\n")))
  1710.           (if (fboundp el)
  1711.           (setq ret (concat ret (prin1-to-string (symbol-function el)) 
  1712.                     "\n"))))))
  1713.     (save-excursion
  1714.       (set-buffer (get-buffer-create "*forms-mode debug*"))
  1715.       (if (zerop (buffer-size))
  1716.           (emacs-lisp-mode))
  1717.       (goto-char (point-max))
  1718.       (insert ret)))))
  1719.  
  1720. ;;; forms.el ends here.
  1721.